package myservice.android.activities;

import java.io.File;
import java.util.Calendar;

import myservice.android.Global;
import myservice.android.R;
import myservice.android.database.Database;
import myservice.android.utilities.CustomExceptionHandler;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CalendarActivity extends PickDateActivity {
	
	private Button interestedButton;
	private Button settingsButton;
	private Button publicationsButton;
	private Button timerButton;
	private Button territoriesButton;
	private Button reportsButton;	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {    	
        super.onCreate(savedInstanceState);
        
        // Show the top and bottom button bars
        LinearLayout bar = (LinearLayout) findViewById(R.id.topBar);
        bar.setVisibility(View.VISIBLE);
        bar = (LinearLayout) findViewById(R.id.bottomBar);
        bar.setVisibility(View.VISIBLE);
        
        // Create "MyService" folder on SD card if possible
        createMyServiceFolder();
        
        // When an uncaught exception occurs, dump the LogCat to the log file
        if (Global.folderMyServiceExists)
        	Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler());                    	
    	
    	// Connect to the database
    	Database.context=this;
        Database.openConnection();
        
        // Load settings
    	Global.loadSettings();    	
    	
    	// Load month names
    	Global.monthNames=Global.res.getStringArray(R.array.array_month_names);    	
    	Global.monthNamesShort=Global.res.getStringArray(R.array.array_month_names_short);     	
                
        windowTitle.setText(Global.res.getString(R.string.app_name));        
        
        interestedButton = (Button) findViewById(R.id.interestedButton);        
        settingsButton = (Button) findViewById(R.id.settingsButton);
        publicationsButton = (Button) findViewById(R.id.publicationsButton);
        timerButton = (Button) findViewById(R.id.timerButton);
        reportsButton = (Button) findViewById(R.id.reportsButton);
        territoriesButton = (Button) findViewById(R.id.territoriesButton);
        
        // Retrieve day names above week days
        dayLabels[0] = (TextView) findViewById(R.id.dayLabel0);
        dayLabels[1] = (TextView) findViewById(R.id.dayLabel1);
        dayLabels[2] = (TextView) findViewById(R.id.dayLabel2);
        dayLabels[3] = (TextView) findViewById(R.id.dayLabel3);
        dayLabels[4] = (TextView) findViewById(R.id.dayLabel4);
        dayLabels[5] = (TextView) findViewById(R.id.dayLabel5);
        dayLabels[6] = (TextView) findViewById(R.id.dayLabel6);                                           
        
        interestedButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				Intent i = new Intent(getApplicationContext(), PersonListActivity.class);
				i.putExtra("mode",0); //Indicates that the user wants modify to interested persons, not pick a person from the list			
				startActivity(i);
			}        	
        });
        
        territoriesButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				Intent i = new Intent(getApplicationContext(), TerritoryListActivity.class);
				i.putExtra("mode",0); //Indicates that the user wants modify territories, not pick a territory from the list			
				startActivity(i);
			}        	
        });        
        
        publicationsButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				Intent i = new Intent(getApplicationContext(), PublicationListActivity.class);
				i.putExtra("person_id",0); //Indicates that owned publications should not be displayed			
				startActivity(i);
			}        	
        });   
        
        reportsButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				Intent i = new Intent(getApplicationContext(), ReportsActivity.class);
				i.putExtra("month", calendar.get(Calendar.MONTH));
				i.putExtra("year", calendar.get(Calendar.YEAR));
				startActivity(i);
			}        	
        });        
        
        timerButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				Intent i = new Intent(getApplicationContext(), TimerActivity.class);			
				startActivity(i);
			}        	
        });        
        
        settingsButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				 Intent i = new Intent(getApplicationContext(),SettingsActivity.class);
			     startActivity(i);
			}        	
        });        			
		
        // Tooltips
        interestedButton.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View button) {
				Global.displayToast(CalendarActivity.this, Global.res.getString(R.string.tip_manage_persons));
				return true;
			}        	
        });
        
        settingsButton.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View button) {
				Global.displayToast(CalendarActivity.this, Global.res.getString(R.string.tip_settings));
				return true;
			}        	
        }); 
        
        publicationsButton.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View button) {
				Global.displayToast(CalendarActivity.this, Global.res.getString(R.string.tip_manage_publications));
				return true;
			}        	
        });  
        
        timerButton.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View button) {
				Global.displayToast(CalendarActivity.this, Global.res.getString(R.string.tip_timer));
				return true;
			}        	
        }); 
        
        territoriesButton.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View button) {
				Global.displayToast(CalendarActivity.this, Global.res.getString(R.string.tip_manage_territories));
				return true;
			}        	
        });    
        
        reportsButton.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View button) {
				Global.displayToast(CalendarActivity.this, Global.res.getString(R.string.tip_reports));
				return true;
			}        	
        });  
        
    	// Check if database needs to be backed up to SD card (if SD card exists)
    	if (Global.autoBackupData && Global.folderMyServiceExists) {
    		if (Database.checkDatabaseBackup())
    			Global.displayToast(this, Global.res.getString(R.string.message_data_backed_up));
    	}        
        
    }
    
    @Override
    protected void clickDate(int date) {
		int month = calendar.get(Calendar.MONTH);
		int year = calendar.get(Calendar.YEAR);	
		Intent i = new Intent(getApplicationContext(),MinistryDetailsActivity.class);
		i.putExtra("date",date);
		i.putExtra("month",month);
		i.putExtra("year",year);					    
		startActivity(i);
    }    
    
    @Override
    public void onResume() {
    	super.onResume();    	
        
        //Update the timer button depending on whether it is started or not
        Cursor c = Database.select("SELECT value FROM settings WHERE name='timerstart'");
        c.moveToNext();
        if (c.getInt(c.getColumnIndex("value"))==0)
        	timerButton.setBackgroundDrawable(Global.res.getDrawable(R.drawable.timer_button));
        else {
        	timerButton.setBackgroundResource(R.drawable.timer_animation);
        	AnimationDrawable frameAnimation = (AnimationDrawable) timerButton.getBackground();
        	frameAnimation.start();
        	Log.d(Global.TAG,"Starting animation!");
        }
        c.close();
        
    }    			
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i(Global.TAG,"Shutting down MyService...");
		Global.saveSettings();
		Database.closeConnection();		
		Global.dumpLogToFile(null);
	}			
    
    /**
     * Creates the "MyService" folder on the SD card, if available
     */
    private void createMyServiceFolder() {    	    	
    	
    	if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
    		return;
    	
    	File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/MyService");
    	
    	if (dir.exists()) {
    		Global.folderMyServiceExists = true;
    		return;
    	}
    	
    	if (dir.mkdir()) {
    		Log.i(Global.TAG,"'MyService' folder created on the SD card.");
    		Global.folderMyServiceExists = true;
    	}
    	
    }
    
}